package com.frame.work.frame.deal.gateway;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.frame.work.common.base.core.CoreServer;
import com.frame.work.common.util.FrameMaker;
import com.frame.work.entity.TblGateway;
import com.frame.work.mapper.TblGatewayMapper;
import com.frame.work.mqtt.data.handle.MqttDataHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

@Component
public class Gateway_50_frame_deal {
    @Autowired
    private CoreServer coreServer;
    @Autowired
    private MqttDataHandle mqttDataHandle;

    @Autowired
    private TblGatewayMapper gatewayMapper;


    public void frameDeal(String gatewayMac, String data, Object channel) {
        String dataToGatewayMac = data.substring(2, 18); // 网关mac
        String child_cmd = data.substring(20, 22); // 子命令标识
        if (child_cmd.equals("05")) { // 布防、撤防响应 50 F5DDE70D006F0D00 03 05 00 00
            // 获取网关状态信息
            coreServer.writeDataToGateWay(FrameMaker.getReadGateway50Frame(gatewayMac), channel);
        } else if (child_cmd.equals("03")) {// 网关状态 50 F5DDE70D006F0D00 06 03 FF 00 FFFF 02 02
            String defendStatus = data.substring(30, 32); // 布防状态 01 布防 02 撤防
            String alarmStatus = data.substring(32, 34); // 报警状态 01 报警 02 非报警
            //修改数据库布防撤防以及报警信息
            TblGateway gateway = TblGateway.builder().defendStatus(defendStatus).alarmStatus(alarmStatus).build();
            int update = gatewayMapper.update(gateway, Wrappers.<TblGateway>lambdaQuery()
                    .eq(TblGateway::getZigbeeMac, dataToGatewayMac));
            if (update < 1) {
                System.out.println("设备信息修改失败" + dataToGatewayMac);
            }
            TblGateway tblGateway = gatewayMapper.selectOne(Wrappers.<TblGateway>lambdaQuery()
                    .eq(TblGateway::getZigbeeMac, dataToGatewayMac));
            if (tblGateway != null) {
                Map<String, Object> objectMap = new HashMap<>();
                objectMap.put("gatewayId", tblGateway.getId());
                objectMap.put("homeId", tblGateway.getHomeId());
                objectMap.put("defendStatus", defendStatus);
                mqttDataHandle.mqttPush(gatewayMac, JSONObject.toJSONString(objectMap));

                //这边忘了啥时候用的
                Map<String, Object> objectMap_px = new HashMap<>();
                objectMap_px.put("gatewayId", tblGateway.getId());
                objectMap_px.put("homeId", tblGateway.getHomeId());
                objectMap_px.put("defendStatus", defendStatus);
                mqttDataHandle.mqttPush("fx_" + gatewayMac, JSONObject.toJSONString(objectMap));
            }
        }
    }
}